package com.atguigu.flink.chapter10;

import com.atguigu.flink.bean.OrderEvent;
import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.util.KKutil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

public class Flink03_Project_Order {
       public static void main(String[] args) {
               Configuration configuration = new Configuration();
               //web  UI端口
               configuration.setInteger("rest.prot",10000);
               StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
               env.setParallelism(1);

           KeyedStream<OrderEvent, Long> stream = env.readTextFile("input/OrderLog.csv")
                   .map(line -> {
                       String[] datas = line.split(",");
                       return new OrderEvent(
                               Long.valueOf(datas[0]),
                               datas[1],
                               datas[2],
                               Long.valueOf(datas[3])
                       );
                   })
                   .assignTimestampsAndWatermarks(WatermarkStrategy
                           .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                           .withTimestampAssigner((log, es) -> log.getEventTime())
                   )
                   .keyBy(OrderEvent::getOrderId);


           Pattern<OrderEvent, OrderEvent> pattern = Pattern
                   //在 create 后面  增加跳过策略
                   .<OrderEvent>begin("create", AfterMatchSkipStrategy.skipPastLastEvent())
                   .where(new SimpleCondition<OrderEvent>() {
                       @Override
                       public boolean filter(OrderEvent value) throws Exception {
                           return "create".equals(value.getEventType());
                       }
                   })
                   .optional()
                   .next("pay")
                   .where(new SimpleCondition<OrderEvent>() {
                       @Override
                       public boolean filter(OrderEvent value) throws Exception {
                           return "pay".equals(value.getEventType());
                       }
                   }).within(Time.minutes(30));

           PatternStream<OrderEvent> ps  = CEP.pattern(stream, pattern);

           SingleOutputStreamOperator<String> result = ps.select(
                   new OutputTag<String>("singleCreate") {},

                   new PatternTimeoutFunction<OrderEvent, String>() {
                       @Override
                       public String timeout(Map<String, List<OrderEvent>> pattern, long timeoutTimestamp) throws Exception {
                           OrderEvent create = pattern.get("create").get(0);

                           return create.getOrderId() + " 只有create没有pay或者pay超时....";
                       }
                   }
                   , new PatternSelectFunction<OrderEvent, String>() {
                       @Override
                       public String select(Map<String, List<OrderEvent>> pattern) throws Exception {
                           //正常匹配： pay和create都正常，只有pay没有create
                           if (!pattern.containsKey("create")) {
                               return pattern.get("pay").get(0).getOrderId() +"只有pay没有create";
                           }else {return "";}


                       }
                   });
           // 过滤掉 正常中  空白的位置
         //  result.filter(a -> a.length() >0).print("正常");
          // result.getSideOutput(new OutputTag<String>("singleCreate") {}).print("异常");

           //合并流
           result.filter(a -> a.length() >0)
                   .union(result.getSideOutput(new OutputTag<String>("singleCreate") {}))
                           .print();

        // 结果如下  如果不想要  重复出现，可以在侧输出流 返回一个异常事件的Map，最后打印的时候，只输出一个异常问题的id

         /*  200只有pay没有create
           100只有pay没有create
           100 只有create没有pay或者pay超时....
           34768 只有create没有pay或者pay超时....*/



           try {
                   env.execute();
               } catch (Exception e) {
                   e.printStackTrace();
               }


           }
}
